import { ajax, Login } from '../utils/ajax.js'
import '../lib/jquery.js'
import { nickTest, ageTest } from '../utils/register.js'

//进去页面自调用
(async () => {
    let { status, user, token } = await Login();
    if (status == 0) {
        alert('请登录！')
        location.href = './login.html';
    }

    //将用户名和昵称渲染到输入框中
    $('.username').val(user.username)
    $('.nickname').val(user.nickname)

    //表单提交
    $('form').on('submit', async e => {
        //防止真的提交
        e.preventDefault();

        let age = $('.age').val();
        let nickname = $('.nickname').val();
        let gender = $('.gender').val();

        //先判空
        if (age == '') return alert('年龄不能为空');
        if (nickname == '') return alert('昵称不能为空');
        if (gender == '') return alert('性别不能为空');

        //再判断格式，性别可以选不用判断了
        if (!nickTest(nickname)) return alert('昵称格式不对！');
        if (!ageTest(age)) return alert('年龄不合理');

        //携带的数据
        let data = { id : user.id, age, gender, nickname };
        //老规矩传给服务器修改
        let { data: {code} } = await ajax.post('/users/update', data, { headers: { authorization: token } })
        if (code == 0) {
            alert('修改失败！')
        }
        alert("修改成功")
    })
})()